<template>
  <div  class="wrapper">
    <BreakSpace label="基本信息" :containerStyle="{ marginBottom: '15px' }" />
    <div style="height:300px">
      <FormPanel
        ref="from"
        :list="initForm"
        :cols="3"
        :formType="value.type"
        :labelWidth="120"
        :isSubmitBtn="false"
        :collapse="false"
        @formChange="changeHandle"
      />
    </div>

    <BreakSpace label="配件信息" :containerStyle="{ marginBottom: '15px' }" />
    <FilterTable
      height="auto"
      ref="tablePeij"
      :columns="partColumns"
      :isSelectColumn="isSelectColumn"
      selectionType="single"
      :isMemoryPagination="true"
      :onSyncTableData="syncPjFun"
      :datakey="'records'"
      :isToperInfo="false"
      :onColumnsChange="partColumns => (this.partColumns = partColumns)"
      columnsRef="notification_maintain_info_02"
    >
      <template slot="controls">
        <el-button size="small" v-if="this.oderseach" type="primary" icon="el-icon-plus" @click="seacherFun()">添加配件</el-button>
        <el-button size="small" v-if="this.oderseach" type="primary" icon="el-icon-plus" @click="openimportPjDialog">导入配件
        </el-button>
      </template>
    </FilterTable>


    <BaseDialog
      :visible.sync="visiblePartOrder"
      :title="'采购订单查询'"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">

      <partOrder @close="closeFun(1)" @selectedOrder="selectedFun" />
    </BaseDialog>

    <BaseDialog
      title="选择配件"
      :visible.sync="visiblePartsGroup"
      width="1000px"
      destroyOnClose
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">

      <partInfo v-model="searchData" @close="closeFun(2)" @selectedPart="selectedPartFun" />
    </BaseDialog>

    <BaseDialog style="min-height: 80vh;" :visible.sync="visibleImportPeij" width="80vw" title="配件导入" destroyOnClose
                :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '50px' }"
    >
      <ExcelImport
        ref="import"
        template-file-name="配件导入模板.xlsx"
        :importRules="importRules"
        :onBeforeDownloadTemp="setParts"
        :onComplete="importComplete"
        @close="visibleImportPeij = false"
      />
    </BaseDialog>

    <div class="dialogBottmView">
      <el-button @click="closeDialog('closeDialog')">关 闭</el-button>
      <el-button :loading="loadingFlag" @click="saveDialog('50051001')" type="primary">保 存</el-button>
      <el-button :loading="loadingFlag" @click="saveDialog('50051002')" type="primary">提 交</el-button>
    </div>
  </div>
</template>

<script>
import { getFileGroup } from '@/api/partsmanage/common/file';
import {saveReturnInfo,getPartsByReturnID,getPartInfo,imReturnPart} from '@/api/partsmanage/saleReturnManage/index';
import { phone} from '@/utils/validate'
import moment from 'moment';
import { dictionary } from '@/utils/dictMixin';
import partOrder from './partOrder'
import partInfo from './partInfo'
import ExcelImport from '@/components/ExcelImport';
export default {
  name: "returnInfo",
  mixins: [dictionary],
  components:{
    partOrder,
    ExcelImport,
    partInfo
  },
  props:{
    value: {
      type: Object,
      data: Object,
      required: true
    },
  },
  data() {
    return {
      type: this.value.type,
      initForm : this.initFormFun(),
      partColumns: this.creatHeaderPartRoleColumns(),
      importRules: this.initImportRuleFun(),
      partList: [],
      isSelectColumn: false,
      visibleImportPeij: false,
      initPartData: {},
      visiblePart: false,
      visiblePartOrder: false,
      visiblePartsGroup: false,
      oderseach: false,
      formData:{},
      searchData: {},
      returnID: '',
      saveData: {
        bkpzsl: 0,
        bkztze: 0,
        partList: []
      },
      djzt: null,
      loadingFlag:false,
    };
  },
  created() {
    this.init(this.value.data)
  },
  methods: {
    init(data) {
      if(this.type==='edit'){
        this.returnID = data.id
        var initdata = {
          id: data.id,
          bkthlx: data.bkthlx,
          ownerCode: data.ownerCode
        }
        this.djzt = data.bkxtzt
        getPartsByReturnID(initdata).then(response => {
          var list = response.data
          if(response.resultCode === 200){
            this.$nextTick(()=>{
              this.$refs.tablePeij.EXECUTE_INSERT(list)
            })
          }
        })
        this.initForm.forEach(x => {
          if (x.fieldName === 'created_at') {
            x.initialValue = moment(data.createdAt).format('YYYY-MM-DD HH:mm:ss');
          } else if (x.fieldName === 'bkthlx'){
            x.initialValue = data[x.fieldName];
            if(data[x.fieldName] === 50041004 || data[x.fieldName] === 50041005){
              this.oderseach = true
            }
          } else {
            x.initialValue = data[x.fieldName];
          }
        });
        getFileGroup({ "xtdjid": this.returnID, "xtfjlx": "5" }).then(response => {
          var fileList = response.data.records
          this.initForm.forEach(x => {
            if (x.fieldName === 'wayFiles') {
              x.initialValue = fileList
            }
          })
        })
      }
    },
    initFormFun(){
      return [
        {
          type: 'INPUT',
          label: '退货单号',
          fieldName: 'bkxtdh',
          disabled: true,
          hidden: this.value.type === 'add'
        },
        {
          type: 'SELECT',
          label: '退货类型',
          fieldName: 'bkthlx',
          placeholder: '请选择',
          clearable: false,
          initialValue: 50041001,
          itemList: this.createDictList('5004'),
          change: val => {
            this.lxChange(val);
          },
          rules: [{
            required: true,
            message: '必填',
            trigger: 'change'
          }]
        },
        {
          type: 'INPUT',
          label: '创建日期',
          fieldName: 'created_at',
          placeholder: '请输入',
          initialValue:  moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
          disabled: true
        },
        {
          type: 'INPUT',
          label: '经办人',
          fieldName: 'bkjbry',
          placeholder: '请输入',
          initialValue: '',
          rules: [{
            required: true,
            message: '必填',
            trigger: 'blur'
          }]
        },
        {
          type: 'INPUT',
          label: '经办人电话',
          fieldName: 'bkrydh',
          placeholder: '请输入',
          initialValue: '',
          rules: [{
            required: true,
            message: '必填',
            trigger: 'blur'
          },
          { trigger: 'blur', validator: phone }]
        },
        {
          type: 'INPUT',
          label: '采购单号',
          fieldName: 'bkysdj',
          placeholder: '请输入',
          initialValue: '',
          readonly:true,
          unitRender: () => {
            if(!this.oderseach){
              return (
                <div>
                  <el-button icon="el-icon-search" onClick={() => this.visiblePartOrder = true}></el-button>
                </div>
              );
            }
          }
        },
        {
          type: 'TEXT_AREA',
          label: '退货原因',
          fieldName: 'bkxtly',
          placeholder: '请输入',
          selfCols:3
        },
        {
          selfCols: 3,
          type: 'UPLOAD_FILE',
          label: '上传文件',
          fieldName: 'wayFiles',
          placeholder: '上传文件...',
          // rules: [{ required: true, message: '请上传文件', trigger: 'change' }],
          // initialValue: [{ name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100' }],
          initialValue: '',
          upload: {
            actionUrl: '/api/file/oss/upload',
            limit: 1,
            tipText: '（支持：PDF、RAR、JPG格式）'
          }
        }
      ]
    },
    initImportRuleFun() {
      return [
        {
          prop: 'bjxmbh', title: '配件代码',
          rule: [
            {required: true, message: '配件代码不能为空'}
          ]
        },
        {
          prop: 'bjzwmc', title: '配件名称'
        },
        {
          prop: 'xsddhm', title: '配件订单号'
        },
        {
          prop: 'bjpjsx', title: '配件属性',
          rule: [
            {required: true, message: '配件属性不能为空'},
            {itemList: this.createDictList('5000')}
          ]
        },
        {
          prop: 'bsspsl', title: '采购数量'
        },
        {
          prop: 'pjkykc', title: '可用库存'
        },
        {
          prop: 'bkthsl', title: '退货数量',
          rule: [
            {required: true, message: '退货数量不能为空'},
            {pattern: /(^[1-9]\d*$)/, message: '请填写正确的退货数量'}
          ]
        }
      ]
    },
    lxChange(val) {
      this.oderseach = false
      // 呆滞件退货 退网退货
      if(val === 50041004 || val === 50041005){
        this.oderseach = true
      }
      this.initForm.forEach(x => {
        if (x.fieldName === 'bkysdj') {
          x.initialValue = null
        }
      });
      if (this.formData.details.length>0) {
        this.$refs.tablePeij.SET_TABLE_DATA([]) //改变类型就清空配件明细
        // this.$confirm('切换订单类型将导致配件明细会被清空！').then(r => {
        //   this.$refs.tablePeij.SET_TABLE_DATA([]) //改变类型就清空配件明细
        // })
      }
    },
    creatHeaderPartRoleColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          fixed: 'left',
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 50,
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.deletePart(props.row,props.$index)}>
                  删除
                </el-button>
              </div>
            );
          }
        },
        { title: '厂家发货仓库名称', fixed: 'left', dataIndex: 'bsckmc', sorter: true },
        { title: '配件id', dataIndex: 'bjpjid', hidden: true },
        { title: '配件代码', fixed: 'left', dataIndex: 'bjxmbh', sorter: true },
        { title: '配件名称', fixed: 'left', dataIndex: 'bjzwmc', sorter: true },
        // { title: '可退货数量', dataIndex: 'pjktsl', sorter: true },
        { title: '采购数量', dataIndex: 'bsspsl', sorter: true },
        { title: '库存数量', dataIndex: 'pjkykc', sorter: true },
        { title: '采购单价', dataIndex: 'jjhdj', sorter: true },
        { title: '折扣率', dataIndex: 'pjzkl', sorter: true },
        { title: '折扣后单价', dataIndex: 'bsxszk', sorter: true },
        // { title: '采购单号', dataIndex: 'xsddhm', sorter: true },
        {
          title: '退货数量',
          dataIndex: 'bkthsl',
          filterType: 'input',
          sorter: true,
          editable: true,
          editType: 'number',
          editPattern: /(^[1-9]\d*$)/,
          editValidator:(val, row, callback) => {
            if (Number(val) <= 0) {
              return callback(new Error('退货数量需大于0'))
            }
            if (Number(val) <= Number(row.pjkykc)) {
              if(this.oderseach){ //呆滞件，退网
                callback()
              } else {
                if(Number(val) <= Number(row.bsspsl) ){
                  callback()
                } else {
                  callback(new Error('退货数量要小于可退数量！'))
                }
              }
            } else {
              return callback(new Error('退货数量要小于可用库存！'))
            }
            row.bkzonj = Number(row.bsxszk) * Number(row.bkthsl);
            // row.bkzonj = (Number(row.jjhdj) *Number(row.pjzkl) * Number(row.bkthsl)/100).toFixed(2);
          }
        },
        { title: '实际退货金额', dataIndex: 'bkzonj', sorter: true },
        { title: '配件属性', dataIndex: 'bjpjsx', sorter: true, render: props => { return <span>{this.createDictText(props.row.bjpjsx, '5000')}</span>; } }
      ];
    },
    seacherFun() {
      if(this.validForm()){
        this.visiblePartsGroup = true;
      }
    },
    selectedFun(val){
      this.initForm.forEach(x => {
        if (x.fieldName === 'bkysdj') {
          if((x.initialValue !== '' && x.initialValue !== null) && (x.initialValue !== val[0].xsddhm)){
            // this.$confirm('采购单号改变将导致配件明细会被清空！').then(r => {
              this.$refs.tablePeij.SET_TABLE_DATA([]) //采购单号就清空配件明细
              x.initialValue = val[0].xsddhm
              this.searchData.bkysdj = val[0].xsddhm
              this.visiblePartOrder = false
              this.visiblePartsGroup = true;
            // }).catch(() => {
            //   this.$message({
            //     type: 'info',
            //     message: '已取消'
            //   });
            // });
          } else {
            x.initialValue = val[0].xsddhm
            this.searchData.bkysdj = val[0].xsddhm
            this.visiblePartOrder = false
            this.visiblePartsGroup = true;
          }
        }
        if(x.fieldName === 'bkthlx') {
          this.searchData.bkthlx = x.initialValue
        }
      });
    },
    changeHandle(val){
      this.saveData=val
    },
    deletePart(row,index) {
      this.$confirm('确认删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        this.$refs.tablePeij.EXECUTE_DELETE([row])
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      })
      .catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    closeFun(val) {
      if (val === 1) { // 查询采购单号
        this.visiblePartOrder = false
      } else if (val === 2) { // 查询配件
        this.visiblePartsGroup = false;
      }
    },
    selectedPartFun(val) {
      var sameFlag = false
      val.forEach(x => {
        x.flag = true
        this.formData.details.forEach(item => {
          if (item.bjpjid === x.bjpjid) {
            x.flag = false
            sameFlag = true
          }
        })
      })
      val.forEach(x => {
        x.bkzonj = 0
        // x.bkthsl = 0
        x.bsxszk = (x.jjhdj * x.pjzkl/100).toFixed(2)
        if (x.flag === true) {
          this.$refs.tablePeij.EXECUTE_INSERT(x)
        }
      })
      this.visiblePartsGroup = false;
    },
    syncPjFun(details){
      this.formData.details = details
    },
    //保存
    async saveDialog(val) {
      // this.$refs.from.SUBMIT_FORM();
      let [err, data] = await this.$refs.from.GET_FORM_DATA();
      const err1 = this.$refs.tablePeij.GET_REQUIRED_ERROR();
      const err2 = this.$refs.tablePeij.GET_FORMAT_ERROR();
      if(err || err1|| err2) return;
      if (this.saveData) {
        this.saveData.editType = this.type
        this.saveData.bkxtzt = val
        this.saveData.partList = this.formData.details
        this.saveData.bkthxm = this.formData.details.length
        this.saveData.id = this.returnID
        if (this.saveData.partList === null || this.saveData.partList === undefined || this.saveData.partList === [] || this.saveData.partList.length === 0) {
          this.$notify.error({title: '提示信息',message:'请添加配件'||'保存失败!'});
          return false;
        }

        this.loadingFlag = true;
        await this.getTotal(data)
        let res =await saveReturnInfo(this.saveData)

        if (res.resultCode === 200) {
          this.$notify.success({title: '提示信息',message:'保存成功!'});
          this.loadingFlag = false;
          this.closeDialog('refresh')
        } else {
          this.$notify.error({title: '提示信息',message:res.errMsg||'保存失败!'});
        }
      }
    },
    //取消操作
    closeDialog(type) {
      this.$emit('close', type);
    },
    getTotal(item){
      var totalNum = 0
      var totalMoney = 0
      var pjddh
      this.saveData.partList.forEach(i => {
        totalNum = totalNum + Number(i.bkthsl);
        totalMoney = totalMoney + Number(i.bkzonj);
        if(i.xsddhm !== null && i.xsddhm !== '' && i.xsddhm !==undefined ){
          pjddh = i.xsddhm
        }
      })
      this.saveData.bkxtze = totalMoney
      this.saveData.bkpzsl = totalNum
      this.saveData.bkjbry = item.bkjbry
      this.saveData.bkrydh = item.bkrydh
      this.saveData.bkthlx = item.bkthlx
      this.saveData.bkxtly = item.bkxtly
      // this.saveData.bkysdj = item.bkysdj
      this.saveData.created_at = item.created_at
      this.saveData.wayFiles = item.wayFiles
      if(item.bkysdj !== null && item.bkysdj !== '' && item.bkysdj !==undefined ){
        this.saveData.bkysdj = item.bkysdj
      } else {
        this.saveData.bkysdj = pjddh
      }
    },
    /* 添加配件明细之前的验证 */
    validForm() {
      var flag = false;
      var bkysdj;
      var bkthlx;
      this.initForm.forEach(x => {
        if (x.fieldName === 'bkysdj') {
          if (x.initialValue === '' || x.initialValue === null || x.initialValue === undefined) {
            flag = true;
          }
          bkysdj = x.initialValue
        }
        if (x.fieldName === 'bkthlx') {
          bkthlx = x.initialValue
        }
      });
      if(!this.oderseach && flag){
        this.$notify.error({ title: '提示信息', message: '请先选择采购单号' || '操作失败!' });
        return false;
      } else {
        this.searchData =  {
          bkysdj: bkysdj,
          bkthlx: bkthlx
        };
        return true;
      }

    },
    /* 打开导入配件Dialog */
    openimportPjDialog() {
      if (this.validForm()) {
        this.visibleImportPeij = true;
      }
    },
    setParts(callback) {
      // 查询所有
      this.searchData.type = 'unlimit'
      getPartInfo(this.searchData).then(res => {
        res.data.records.forEach(i => {
          i.bjpjsx = this.createDictText(i.bjpjsx, '5000')
        })
        callback(res.data.records)
      })
    },
    importComplete(datas, callback) {
      var bkthlx;
      this.initForm.forEach(x => {
        if (x.fieldName === 'bkthlx') {
          bkthlx = x.initialValue
        }
      });
      const errorData = []
      datas.forEach((item, index1) => {
        const indexarr = []
        datas.forEach((i, index2) => {
          if (
            i.bjxmbh === item.bjxmbh &&
            i.bjpjsx === item.bjpjsx &&
            index1 !== index2) {
            indexarr.push(index2 + 1)
          }
        })
        if (indexarr.length) {
          errorData.push({
            rownum: index1 + 1,
            errormsg: `配件信息和${indexarr.join(',')}行重复`
          })
        }
      })
      if (errorData.length) {
        callback(errorData)
      }
      else {
        var importData = {
          datas: datas,
          bkthlx: bkthlx,
          type: 'add'
        }
        imReturnPart(importData).then(res => {
          if(res.status){
            this.visibleImportPeij = false
            this.$notify.success({title: '提示信息', message: '导入验证成功'});
            this.selectedPartFun(res.data)
            callback()
          }else{
            callback(res.data)
          }
        })
      }
    },
  }
};
</script>
<style scoped>
.wrapper {
  height: calc(100vh - 110px);
}
</style>
